<template>
  <a-form-model
    ref="ruleForm"
    :model="form"
    :rules="rules"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
  >
    <a-form-model-item ref="name" label="活动名称" prop="name">
      <a-input v-model="form.name">
        <a-icon slot="suffix" type="flag"></a-icon>
      </a-input>
    </a-form-model-item>
    <a-form-model-item ref="name" label="活动地点" prop="position">
      <a-input v-model="form.position">
        <a-icon slot="suffix" type="global"></a-icon>
      </a-input>
    </a-form-model-item>

    <a-form-model-item label="活动时间" required>
      <a-range-picker
        :show-time="{ format: 'HH:mm' }"
        format="YYYY-MM-DD HH:mm"
        @change="onChange"
        :placeholder="['Start Time', 'End Time']"
      >
        <a-icon slot="suffixIcon" type="calendar" />
      </a-range-picker>
      <!-- <a-date-picker
          v-model="form.date1"
          show-time
          type="date"
          placeholder="Pick a date"
          style="width: 100%"
        /> -->
    </a-form-model-item>

    <a-form-model-item label="活动简介" prop="desc">
      <a-input v-model="form.desc" type="textarea" />
    </a-form-model-item>
    <a-form-model-item class="upload" label="活动图片" prop="pics">
      <a-upload
        multiple
        list-type="picture-card"
        :before-upload="beforeUpload"
        :file-list="form.fileList"
        @preview="handlePreview"
        @change="handleChange"
      >
        <div v-if="form.fileList.length < 5">
          <a-icon type="plus" />
          <div class="ant-upload-text">Upload</div>
        </div>
      </a-upload>
      <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </a-form-model-item>

    <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" @click="onSubmit" :loading="uploading">
        Create
      </a-button>
      <a-button style="margin-left: 10px" @click="resetForm"> Reset </a-button>
    </a-form-model-item>
  </a-form-model>
</template>

<script>
import RequestUtil from "../../../utils/requestUtils";

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
export default {
  name: "Publish",
  data() {
    return {
      asideAttrs: {
        title: "Publish",
        menuItems: [
          {
            iconType: "fire",
            iconTheme: "filled",
            name: "Popular",
            link: "/popular",
          },
          {
            iconType: "thunderbolt",
            iconTheme: "filled",
            name: "Latest",
            link: "/latest",
          },
          {
            iconType: "star",
            iconTheme: "filled",
            name: "Liked",
            link: "/liked",
          },
          {
            iconType: "flag",
            iconTheme: "filled",
            name: "Publish",
            link: "/publish",
          },
        ],
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 12 },
      other: "",
      previewVisible: false,
      previewImage: "",
      uploading: false,
      form: {
        name: "",
        activityStart: null,
        activityEnd: null,
        desc: "",
        position: "",
        fileList: [],
      },
      rules: {
        position: [
          {
            required: true,
            message: "活动地点不能为空",
            trigger: "change",
          },
        ],
        name: [
          {
            required: true,
            message: "活动名称不能为空",
            trigger: "blur",
          },
          {
            min: 3,
            max: 20,
            message: "字符长度3到20",
            trigger: "blur",
          },
        ],
        desc: [
          {
            required: true,
            message: "活动简介不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
      console.log("file.preview: ", file.preview);
    },
    beforeUpload(file) {
      this.form.fileList = [...this.form.fileList, file];
      return false;
    },
    handleChange({ fileList }) {
      this.form.fileList = fileList;
      console.log("filelist: ", fileList);
    },
    onChange(date, dateString) {
      console.log(date);
      //将时间转换为时间戳
      this.form.activityStart = new Date(dateString[0]).getTime();
      this.form.activityEnd = new Date(dateString[1]).getTime();
    },
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        let that = this;
        if (valid) {
          if(!that.form.activityStart || !that.form.activityEnd){
            that.$message.info("请填写活动时间噢");
            return false;
          }
          //网络请求 发布活动
          that.uploading = true;
          RequestUtil.requestPublishActivity(
            that,
            that.form,
            (res) => {
              console.log(res);
              if (res.status == 200) {
                if (res.data.error_code == 0) {
                  that.$message.success("活动上传成功");
                  return res.data.result;
                } else {
                  console.error(`error_code: ${res.data.error_code}`);
                  console.error(`error_msg: ${res.data.error_msg}`);
                  that.$message.error("哎呀，出错了，请稍后再试");
                  that.uploading = false;

                  return -1;
                }
              } else {
                console.error(`res.status: ${res.status}`);
                that.uploading = false;

                return -1;
              }
            },
            (err) => {
              console.error(err);
              that.$message.error("哎呀，出错了，请稍后再试");
              that.uploading = false;

              return -1;
            }
          );
          that.uploading = false;
        } else {
          console.log("error submit!!");
          that.uploading = false;

          return false;
        }
      });
    },
    resetForm() {
      this.$refs.ruleForm.resetFields();
      this.form.fileList = [];
    },
  },
};
</script>

<style lang="less" scopt>
// .upload {
//   multiple: true;
// }
</style>